package com.enation.app.javashop.consumer.shop.distribution;

import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.consumer.core.event.OrderStatusChangeEvent;
import com.enation.app.javashop.consumer.core.event.TradeIntoDbEvent;
import com.enation.app.javashop.core.base.SettingGroup;
import com.enation.app.javashop.core.base.message.OrderStatusChangeMsg;
import com.enation.app.javashop.core.client.distribution.DistributionOrderClient;
import com.enation.app.javashop.core.client.system.SettingClient;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.dos.DistributionOrderDO;
import com.enation.app.javashop.core.distribution.model.dos.DistributionSetting;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.distribution.service.pattern.DistributionContext;
import com.enation.app.javashop.core.distribution.service.pattern.DistributionStrategy;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanOrderManager;
import com.enation.app.javashop.core.statistics.util.DateUtil;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.dto.OrderDTO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderStatusEnum;
import com.enation.app.javashop.core.trade.order.model.enums.OrderTypeEnum;
import com.enation.app.javashop.core.trade.order.model.vo.OrderSkuVO;
import com.enation.app.javashop.core.trade.order.model.vo.TradeVO;
import com.enation.app.javashop.core.trade.order.service.OrderQueryManager;
import com.enation.app.javashop.framework.util.JsonUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 分销商订单处理
 */
@Component
public class DistributionOrderChangeConsumer implements TradeIntoDbEvent, OrderStatusChangeEvent{

    @Autowired
    private DistributionOrderClient distributionOrderClient;
    @Autowired
    private DistributionManager distributionManager;
    @Autowired
    private SettingClient settingClient;
    @Autowired
    private OrderQueryManager orderQueryManager;
    @Autowired
    private ShetuanOrderManager shetuanOrderManager;

    protected final Log logger = LogFactory.getLog(this.getClass());

    /**
     * 订单入库 创建分销订单
     */
    @Override
    public void onTradeIntoDb(TradeVO tradeVO) {
        List<OrderDTO> orderList = tradeVO.getOrderList();
        if(orderList != null && orderList.size() > 0){
            for (OrderDTO orderDTO : orderList) {
                OrderDO orderDO = orderQueryManager.getModel(orderDTO.getOrderId());
                List<OrderSkuVO> skuList = JsonUtil.jsonToList(orderDO.getItemsJson(), OrderSkuVO.class);

                logger.debug("创建团购订单:" + orderDTO.getOrderId());
                String orderType = orderDO.getOrderType();
                if(orderType.equals(OrderTypeEnum.shetuan.name())||orderDO.getIsShetuan()==1){
                    shetuanOrderManager.confirm(orderDO);
                }

                logger.debug("创建分销订单:" + orderDTO.getOrderId());
                logger.debug("分销订单" + orderDTO.getOrderId() + "sku信息:" + JSON.toJSON(skuList));
                // 买家分销信息
                int buyMemberId = orderDTO.getMemberId();
                DistributionDO distributor = this.distributionManager.getDistributorByMemberId(buyMemberId);

                // 新增分销关联订单
                DistributionOrderDO distributionOrderDO = new DistributionOrderDO();
                distributionOrderDO.setOrderId(orderDTO.getOrderId());
                distributionOrderDO.setBuyerMemberId(buyMemberId);
                distributionOrderDO.setBuyerMemberName(distributor.getMemberName());
                distributionOrderDO.setOrderSn(orderDTO.getSn());
                String setting = settingClient.get(SettingGroup.DISTRIBUTION);
                DistributionSetting ds = JsonUtil.jsonToObject(setting, DistributionSetting.class);
                distributionOrderDO.setSettleCycle((ds.getCycle() * 3600 * 24) + new Long(DateUtil.getDateline()).intValue());
                distributionOrderDO.setOrderPrice(orderDO.getGoodsPrice());
                distributionOrderDO.setCreateTime(orderDTO.getCreateTime());
                distributionOrderDO.setSellerId(orderDTO.getSellerId());

                // 执行策略
                DistributionStrategy distributionStrategy = distributionManager.getDistributionStrategy(orderDO, distributor);
                DistributionContext distributionContext = new DistributionContext(distributionStrategy);
                distributionContext.executeDistributors(orderDO, distributionOrderDO);

                // 保存分销订单
                this.distributionOrderClient.add(distributionOrderDO);
            }
        }
    }


    /**
     * 订单状态改变
     */
    @Override
    public void orderChange(OrderStatusChangeMsg orderStatusChangeMsg) {
        OrderDO order = orderStatusChangeMsg.getOrderDO();
        try {
            if (orderStatusChangeMsg.getNewStatus().equals(OrderStatusEnum.ROG)) {
                distributionOrderClient.confirm(order);
            }
        } catch (Exception e) {
            logger.error("订单收款分销计算返利异常：",e);
        }
    }


}
